package com.itheima.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.AccessLog;
import com.itheima.service.AccessLogService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

public class AccessLogInterceptor implements HandlerInterceptor {
    private Date preDate;
    private Date postDate;
    AccessLog accessLog=new AccessLog();
    @Reference
    AccessLogService accessLogService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        preDate = new Date();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        String uri = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String className=null;
        String methodName=null;
        if (handler instanceof HandlerMethod) {
            className = ((HandlerMethod) handler).getBeanType().getName();
            Method method = ((HandlerMethod) handler).getMethod();
            methodName = method.getName();
        }

        accessLog.setUserName(username);
        accessLog.setIp(ip);
        accessLog.setUri(uri);
        accessLog.setClassName(className);
        accessLog.setMethodName(methodName);
        accessLog.setDate(preDate);


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        postDate = new Date();
        long time = postDate.getTime() - preDate.getTime();
        accessLog.setTime(time);
        accessLogService.add(accessLog);
    }
}
